
<template>
<div class="my-tag">
    <input
    class="input"
    type="text"
    placeholder="输入标签"
    ref="ipt"
    v-if="isEdit"
    @blur="handleClose"
    @keyup.enter="$event.target.blur()"
    :value="value"
    v-focus
    />
    <div v-else class="text" @dblclick="handleClick">{{value}}</div>
</div>
</template>

<script>
export default {
    props:{
        value:[Number,String]
    },
    data(){
        return {
            isEdit:false
        }
    },
    methods:{
        // 1. 自动获取焦点，方式1  $nextTick
        async handleClick(){
            this.isEdit = true
            // await this.$nextTick()
            // 等数据更新完了，获取最新的DOM元素
            // this.$refs.ipt.focus()
        },
        handleClose(e){
            this.isEdit = false
            console.log(e.target.value)
            if(!e.target.value.trim()){
                return alert('内容不能为空哦')
            }
            // :value + @input 
            this.$emit('input', e.target.value)
            
        }
    },
    // 2. 自定义指令的方式，自动获取焦点
    directives:{
        focus:{
            // 当指令所在的元素插入到页面中时，触发
            inserted(el){
                el.focus()
            }
        }
    }
}
</script>

<style lang="less" scoped>
.my-tag {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}
input{
    width: 80px;
}
</style>